﻿using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
/// <summary>
/// 数据处理工具类
/// </summary>
namespace SUNRPA.BROWSER.BRIDGE.util {
    public class DataUtil {
        public static List<T> SliceList<T>(List<T> list, int startIndex, int endIndex) { 
            List<T> result = new List<T>();
            for(int i = startIndex; i < endIndex; i++) { 
                result.Add(list[i]);
            }
            return result;
        }

        public static string GetTextFromStream(Stream stream) {
            using(BufferedStream bs = new BufferedStream(stream)) {
                byte[] bytes = new byte[bs.Length];
                bs.Read(bytes, 0, bytes.Length);
                return Encoding.UTF8.GetString(bytes);
            }
        }
        public static string Btyes2String(byte[] bytes) { 
            return System.Text.Encoding.Default.GetString(bytes);
        }

        public static string ObjectJsonSerializer(object data, bool addTypeName) { 
            JsonSerializerSettings set  = new JsonSerializerSettings();
            if(addTypeName) {
                set.TypeNameHandling = TypeNameHandling.Auto;
            }
            set.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.SerializeObject(data, Formatting.Indented, set);
        }

        public static T DeSerializeJson<T>(string data, bool addTypeName) { 
            JsonSerializerSettings set  = new JsonSerializerSettings();
            if(addTypeName) {
                set.TypeNameHandling = TypeNameHandling.Auto;
            }
            set.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.DeserializeObject<T>(data, set);
        }

        public static string GetCommandLineByProcessId(string processId) {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(
                $"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {processId}")) { 
                using (ManagementObjectCollection objects = searcher.Get()){
                    ManagementBaseObject obj = objects.Cast<ManagementBaseObject>().SingleOrDefault();
                    return obj?["CommandLine"]?.ToString() ?? "";
                }
            }
        }
    }
}
